<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>墨兮</title>
    <link rel="stylesheet" href="../static/css/chat.css">
    <link rel="stylesheet" href="../static/css/prism/prism.css">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <script src="../static/js/prism/prism.js">
        Prism.highlightAll();
    </script>
    <script src="https://cdn.jsdelivr.net/npm/showdown/dist/showdown.min.js"></script>
    <style>
        body {
            background-image: url('../static/image/background.png');
            background-size: cover;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0; /* 重置 body 的外边距 */
            font-family: '楷体', serif;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="left-panel">
        <div class="dialog-header" id="header">参&nbsp;数&nbsp;面&nbsp;板<br><br></div>
        <div>
            <p style="text-align: left; font-size:16px" id="parameter_1"><strong>当前用户：</strong>
                <span style="color: deeppink" id="nowName">{{ gemini.userName }}</span></p>
            <p style="text-align: left; font-size:16px" id="parameter_2"><strong>当前称谓：</strong>
                <span style="color: #00BB33" id="nowCallName">{{ gemini.callName }}</span></p>
            <p style="text-align: left; font-size:16px" id="parameter_3"><strong>当前风格：</strong>
                <span style="color: #007bff" id="nowModelName">{{ gemini.modelType }}</span></p>
            <p style="text-align: left; font-size:16px" id="parameter_4"><strong>当前模型：</strong>
                <span style="color: #007bff" id="nowModel">{{ gemini.choiceModelName }}</span></p>
            <p style="text-align: left; font-size:16px" id="parameter_5"><strong>当前状态：</strong>
                <span style="color: deepskyblue;" id="nowStatue">等待提问</span></p>
            <p style="text-align: left; font-size:16px" id="parameter_6"><strong>回答用时：</strong>
                <span style="color: red;" id="time">0.0</span></p>
        </div>
        <div class="toggle-button" onclick="togglePanel()">
            <img src="../static/image/arrow.png" alt="箭头" width="22" height="22">
        </div>
        <script>
            function togglePanel() {
                let header = document.getElementById("header")
                let parameter_1 = document.getElementById("parameter_1")
                let parameter_2 = document.getElementById("parameter_2")
                let parameter_3 = document.getElementById("parameter_3")
                let parameter_4 = document.getElementById("parameter_4")
                let parameter_5 = document.getElementById("parameter_5")
                let parameter_6 = document.getElementById("parameter_6")

                let userElement = document.getElementById('nowName');
                let callElement = document.getElementById('nowCallName');
                let modelNameElement = document.getElementById('nowModelName');
                let modelElement = document.getElementById('nowModel');
                let statusElement = document.getElementById('nowStatue');
                let timeElement = document.getElementById('time');

                if (!turnOver) {
                    header.style.display = 'none';
                    parameter_1.style.display = 'none';
                    parameter_2.style.display = 'none';
                    parameter_3.style.display = 'none';
                    parameter_4.style.display = 'none';
                    parameter_5.style.display = 'none';
                    parameter_6.style.display = 'none';
                    userElement.style.display = 'none';
                    callElement.style.display = 'none';
                    modelNameElement.style.display = 'none';
                    modelElement.style.display = 'none';
                    timeElement.style.display = 'none';
                    statusElement.style.display = 'none';
                    turnOver = true;
                } else {
                    header.style.display = 'block';
                    parameter_1.style.display = 'block';
                    parameter_2.style.display = 'block';
                    parameter_3.style.display = 'block';
                    parameter_4.style.display = 'block';
                    parameter_5.style.display = 'block';
                    parameter_6.style.display = 'block';
                    userElement.style.display = 'inline';
                    callElement.style.display = 'inline';
                    modelNameElement.style.display = 'inline';
                    modelElement.style.display = 'inline';
                    timeElement.style.display = 'inline';
                    statusElement.style.display = 'inline';
                    turnOver = false;
                }

                const leftPanel = document.querySelector('.left-panel');
                const toggleButton = document.querySelector('.toggle-button');

                leftPanel.classList.toggle('collapsed');
                toggleButton.classList.toggle('collapsed');

            }
        </script>
    </div>
    <div class="dialog-container">
        <div class="dialog-content"></div>
        <div class="input-area">
            <label for="inputs"></label><textarea placeholder="输入内容..." class="message-input"
                                                  id="inputs"></textarea>
            <button class="send-button" onclick="sendMessage(messageInput.value)" disabled>发送</button>
            <button class="stop-button" onclick="stopMessage()" style="display: none;">停止</button>
            <script>
                let messageElement = document.getElementById('inputs');
                messageElement.addEventListener('keydown', function (event) {
                    if (event.ctrlKey && event.key === 'Enter') {
                        if (!(messageElement.value.trim() === "")) {
                            sendMessage(messageElement.value);
                            sendButton.style.display = 'none'; // 隐藏发送按钮
                            stopButton.style.display = 'block';  // 显示停止按钮
                        }
                        event.preventDefault(); // 阻止默认行为，避免换行
                    }
                });
            </script>
            <script>
                async function sendMessage(msg) {
                    // 禁用发送按钮，防止重复发送
                    sendButton.disabled = true;
                    // 清空对话框
                    messageInput.value = "";
                    // 创建新的用户消息元素
                    const userMessageElement = document.createElement('div');
                    userMessageElement.classList.add('message-group', 'user-message');

                    // 转markdown格式:
                    const converter = new showdown.Converter();
                    const html = converter.makeHtml(msg);

                    userMessageElement.innerHTML = `<div class="user-name">{{ gemini.userName }}</div><div class="message">${html}</div>`;

                    // 将用户消息添加到对话框
                    dialogContent.appendChild(userMessageElement);
                    dialogContent.scrollTop = dialogContent.scrollHeight;

                    // 创建新的模型消息元素
                    const modelMessageElement = document.createElement('div');
                    modelMessageElement.classList.add('message-group', 'model-message');
                    modelMessageElement.innerHTML = `<div class="name-message"><div class="model-name">{{ gemini.modelName }}</div><div class="message"><p>...</p></div></div>`;

                    // 将模型消息添加到对话框
                    dialogContent.appendChild(modelMessageElement);
                    Prism.highlightAll()
                    dialogContent.scrollTop = dialogContent.scrollHeight;

                    let spanElement = document.getElementById("nowStatue");
                    spanElement.textContent = "正在回复中..."
                    spanElement.style.color = "red"

                    controller = new AbortController();
                    const signal = controller.signal;

                    let startTime = Date.now(); // 记录开始时间
                    let timerInterval; // 存储计时器 ID，用于清除计时器
                    let elapsedTime = 0; // 存储已经过去的时间

                    let timeElement = document.getElementById("time");
                    timerInterval = setInterval(() => {
                        elapsedTime = Date.now() - startTime;
                        timeElement.textContent = (elapsedTime / 1000).toFixed(1); // 更新显示时间
                    }, 1); // 每 10 毫秒更新一次

                    try {
                        // 发送 POST 请求
                        const response = await fetch('/chatTo', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(
                                {
                                    msg: msg,
                                    username: "{{ gemini.userName }}"
                                }),
                            signal // 将 signal 传递给 fetch
                        });

                        // 获取回复
                        const data = await response.text();

                        // 找到 .message 元素和
                        const messageDiv = modelMessageElement.querySelector('.message');

                        // 逐字输出回复
                        let currentContent = ""; // 用于存储当前已添加的内容
                        for (let i = 0; i < data.length; i++) {
                            setTimeout(() => {
                                currentContent += data[i]; // 将当前字符添加到 currentContent
                                messageDiv.innerHTML = currentContent; // 使用 innerHTML 更新内容
                                // 滚动到底部
                                dialogContent.scrollTop = dialogContent.scrollHeight;
                                if (i === data.length - 1) {
                                    const preElements = document.querySelectorAll('pre');
                                    const lastPreElement = preElements[preElements.length - 1];
                                    lastPreElement.classList.add('line-numbers');
                                    lastPreElement.classList.add('match-braces');
                                    lastPreElement.setAttribute('data-prismjs-copy', '点击复制');
                                    lastPreElement.setAttribute('data-prismjs-copy-success', '复制成功');
                                    Prism.highlightElement(lastPreElement);
                                }
                            }, i * 20); // 可以调整延迟时间，单位为毫秒
                        }
                        setTimeout(() => {
                            Prism.highlightAll();
                        }, data.length * 20 + 10);
                        spanElement.textContent = "等待提问"
                        spanElement.style.color = "deepskyblue"
                        elapsedTime = Date.now() - startTime;
                        timeElement.textContent = (elapsedTime / 1000).toFixed(1);
                    } catch (error) {
                        let errorMsg;
                        if (error.name === 'AbortError') {
                            console.log('请求已中止');
                            errorMsg = "回答已终止";
                        } else {
                            console.error('发送消息出错：', error);
                            errorMsg = "发送消息出错";
                        }
                        timeElement.textContent = "0.0";
                        // 显示错误消息
                        const errorMessageElement = document.createElement('div');
                        errorMessageElement.classList.add('message-group', 'error-message');
                        errorMessageElement.innerHTML = `<div class="name-message"><div class="model-name">{{ gemini.modelName }}</div><div class="message"><p style="color: red">遇到错误啦，请重新询问一遍吧：${errorMsg}</p></div> </div>`;
                        dialogContent.appendChild(errorMessageElement);
                    } finally {
                        // 滚动到底部
                        dialogContent.scrollTop = dialogContent.scrollHeight;
                        stopButton.style.display = 'none';  // 隐藏停止按钮
                        sendButton.style.display = 'block'; // 显示发送按钮
                        clearInterval(timerInterval);
                        Prism.highlightAll();
                    }
                }

                function stopMessage() {
                    if (controller) {
                        controller.abort(); // 中断请求
                        console.log("请求已停止")
                    }
                    stopButton.style.display = 'none';  // 隐藏停止按钮
                    sendButton.style.display = 'block'; // 显示发送按钮
                }
            </script>
            <script>
                stopButton.addEventListener('click', () => {
                    if (controller) {
                        controller.abort(); // 中断请求
                        console.log("请求已停止")
                    }
                    stopButton.style.display = 'none';  // 隐藏停止按钮
                    sendButton.style.display = 'block'; // 显示发送按钮
                });
            </script>
        </div>
    </div>
</div>
<script src="../static/js/chat.js"></script>
<script>
  window.addEventListener('beforeunload', function (event) {
    // 取消事件的默认行为
    event.preventDefault();
  });
</script>
</body>
</html>